package com.panopset.flywheel;

import static com.panopset.UtilIO.*;

import java.io.File;
import java.io.StringWriter;

/**
 * <h5>f - File</h5>
 *
 * <p>
 * Example 1
 * </p>
 *
 * <pre>
 * ${&#064;f someFile.txt}
 * </pre>
 *
 * <p>
 * Example 2
 * </p>
 *
 * <pre>
 * ${&#064;p fileName}someFile.txt${&#064;q}
 * ${&#064;f &#064;fileame}
 * </pre>
 *
 * Output to the specified file, until the end of the template or another file
 * command is found.
 *
 * @author Karl Dinwiddie
 *
 */
public class CommandFile extends MatchableCommand {

    /**
     * Is output to files is enabled. Default is true.
     */
    private static boolean isEnabled = true;

    /**
     * Short HTML text for publishing command format in an HTML document.
     *
     * @return <b>${&#064;f somefile.txt}</b>.
     */
    public static String getShortHTMLText() {
        return "${&#064;f somefile.txt}";
    }

    /**
     * Command File constructor.
     *
     * @param source
     *            Command source.
     * @param innerPiece
     *            Inner piece of the command.
     * @param template
     *            Template this command was declared in.
     */
    public CommandFile(final String source, final String innerPiece,
            final Template template) {
        super(source, innerPiece, template);
    }

    @Override
    public final void resolve(final StringWriter sw) {
        if (getParams() == null) {
            return;
        }
        if (isEnabled) {
            StringWriter newStringWriter = new StringWriter();
            getTemplate().getFlywheel().setWriter(newStringWriter);
            resolveMatchedCommands(newStringWriter);
            saveStringToFile(newStringWriter.toString(), new File(getTemplate()
                    .getFlywheel().getTargetDirectory()
                    + "/" + getParams()));
        } else {
            resolveMatchedCommands(sw);
        }
    }

    /**
     * Disable output to files. This would be used if you want to output to a
     * single String writer.
     */
    public static void disable() {
        isEnabled = false;
    }
}
